<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\EnterpriseWeChat;
use fast\Ftp;
use think\Controller;
use think\Request;
use think\Db;
use \WxworkFinanceSdk;
use wechat\Qywechat;
class Wxwork extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public $corpId = "ww54101b0b95005e2f";
    public $secret = "FgxZE-FheFdaJwsN-a2Ov-QCUHcxefbgv6dGZqosO7E";

    //原有公钥
//    public $PUBLICKey="-----BEGIN PUBLIC KEY-----
//MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAneqSoQ3HLuQrNcb6VLVw
//xkeLqgrH7IyFIJ/pk/1MNI5FNQr3ePKWbcXHmmwr3kwmox3OQS/eT9fbeD4stmVl
//VOOobOruL85aq/jWgAoMR0qEqxkXgVKZZNPN3URqW/bds0LwI4utMLisbLlzSLn0
//is25JamvZszlFUaw+FE3Yf4R+CS5dUwDQDpFKPQutA+TPFUfe5/0+NWnmAxaVAJS
//eAWu1aXTP+egascTrZ2/j1dh26q1d2y9daWmTtDIIuh7zO+boyZFLSM2KrSCrvMY
//AInZaGHDkX+LhVA5151fJDHCWz+DWeWMeXD9JeUoctTB5FcDBzVUw3xWytfk256I
//DQIDAQAB
//-----END PUBLIC KEY-----";


    public $publicKey = "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjMa4mjT1UA2T+cEKaHVH
DMT/AUtfjhfQx0LqRgPmjpjAZ1IE9PqEvX6381xYmmVsCyv2bdsxHCBhjjvNfjE9
o/BRfIahlcm3vm8uRedXnVGll2UoWB2MmMfeSi4V7SimEmsK9SfnboVVTz7oi5aF
NT3+ylgjsGeSfI0+6bF3svQ3PQOUNrsK3Cn8aM2KbYP+xRLFIk9zjWvFJi+WER0X
vIdURtfWDJAWxUt+bpdxbv97JOIIRC1Sbow+SwusRDh/goqfL/eGXv2k6ujqLDtu
+J+mCBUSfyegO2jNyTs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BY+l32FhPo1W
xyIjnY/Y3SXvsw4IQCb67XjwqY5WZJzx8LdCzAryofgf8Hjda5zXO7MYrJk4lwmw
UymuhxwvIh2hlB9rXNns3VkZ72y3W6lvyI1MucsCgYBF2CkIBEyJ/khqjlZm2W8f
QneaqolwpTLS1gwiDIYSmDeBhKit83FEP7VgEz2VKLidikWUnsjixdXiqXGj8C4u
mzlwDNpUpCtc3G/E5wn72rYF6esS9vo16vXy825FKkhLiEFjeu4bEr/9mhGTpBB6
EfHIMV+/zjx3PY0FtLt28wKBgELh01RDthIk8L4YOVSXy9eDFWBaLRyF/lQIiKKk
NiNUImMp3ZaQY4aP04BaQQBM8+7b2NiQhsQh/3qf3MX2HkoqKurgxPtRNenssEyK
seYxfVM1bupBvLaNgBumMw2KB1M9at88K3vBQbcrePF6loy2kzNmdfzepoCxmI7s
2S4lAoGBAJptJAhRt2LpdHAlfD5iR1pzo6+fk1sH4c/qLThSHP4SVDkNrYhM7+uQ
tkJG+gntKs3ELWYoBC8oz31ns/utdbynlx5EDblIp72x6g2303fU+h/timbSHwPI
VV8939ivllDD3yzIG1GLq6jddsVljGY+Ym6flrKKkHruEYHGEem1
-----END RSA PRIVATE KEY-----";
    public function index()
    {
        $seq = Db::connect('CRMDbConfig')->name('corp_wechat_records')->order('id desc')->value('seq');
        $seq = $seq ? $seq : 470990;
        $dir = ROOT_PATH . "public/uploads/workwx/";
        $domain = "";  // 资源文件域名（如图片本地化的域名地址）
        $msgaudit = include_once(EXTEND_PATH . 'workwx/library/src/Api/Struct/Msgaudit/Msgaudit.php');
        $msgaudit->call($this->corpId, $this->secret, $this->privateKey);
        // 从第几条取几条数据出来
        $chatList = $msgaudit->getChatData($seq, 100);

        //logging(__FILE__,$chatList);
        foreach($chatList as $key=>&$val){
            $filename = '';
            if(isset($val['msgtype'])){
                $path = $dir . $val['msgtype'].'/'.date('Ymd') . '/';
                if(!is_dir($path)){
                    mkdir($path,0777,true);
                }
                $show = $content = '';
                switch ($val['msgtype']) {
                    case 'image':
                        // 图片
                        $sdkFileId = $val[$val['msgtype']]["sdkfileid"];
                        $val[$val['msgtype']]['mediaUrl'] = $domain. "/uploads/workwx/{$val['msgtype']}/".date('Ymd')."/{$val['msgid']}.png";
                        $filename = "{$path}{$val['msgid']}.png";

                        $show = $val[$val['msgtype']]['mediaUrl'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'emotion':
                        // 表情
                        $sdkFileId = $val[$val['msgtype']]["sdkfileid"];
                        if($val['emotion']['type']==1){
                            $fileext = 'gif';
                        }else{
                            $fileext = 'png';
                        }
                        $val[$val['msgtype']]['mediaUrl'] = $domain. "/uploads/workwx/{$val['msgtype']}/".date('Ymd')."/{$val['msgid']}.{$fileext}";
                        $filename = "{$path}{$val['msgid']}.{$fileext}";


                        $show = $val[$val['msgtype']]['mediaUrl'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'voice':
                        // 声音
                        $sdkFileId = $val['voice']["sdkfileid"];
                        $val[$val['msgtype']]['mediaUrl'] = $domain. "/uploads/workwx/{$val['msgtype']}/".date('Ymd')."/{$val['msgid']}.amr";
                        $filename = "{$path}{$val['msgid']}.amr";

                        $show = $val[$val['msgtype']]['mediaUrl'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'video':
                        // 视频
                        $sdkFileId = $val['video']["sdkfileid"];
                        $val[$val['msgtype']]['mediaUrl'] = $domain."/uploads/workwx/{$val['msgtype']}/".date('Ymd')."/{$val['msgid']}.mp4";
                        $filename = "{$path}{$val['msgid']}.mp4";
                        $show = $val[$val['msgtype']]['mediaUrl'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'meeting_voice_call':
                        // 音频存档消息
                        $sdkFileId = $val['meeting_voice_call']["sdkfileid"];
                        $val[$val['msgtype']]['mediaUrl'] = $domain."/uploads/workwx/{$val['msgtype']}/".date('Ymd')."/{$val['msgid']}.amr";
                        $filename = "{$path}{$val['msgid']}.amr";
                        $show = $val[$val['msgtype']]['mediaUrl'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'file':
                        // 文件
                        $sdkFileId = $val['file']["sdkfileid"];
                        $val[$val['msgtype']]['mediaUrl'] = $domain. "/uploads/workwx/{$val['msgtype']}/".date('Ymd')."/{$val['msgid']}.{$val['file']['fileext']}";
                        $filename = "{$path}{$val['msgid']}.{$val['file']['fileext']}";
                        $show = $val[$val['msgtype']]['mediaUrl'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'text':
                        $show = $val[$val['msgtype']]['content'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'voiptext':
                        $show = '';
                        $content = '';
                        break;
                    case 'disagree':
                        $show = 'disagree';
                        $content = '';
                        break;
                    case 'agree':
                        $show = 'agree';
                        $content = '';
                        break;
                    case 'qydiskfile':
                        $show = 'qydiskfile';
                        $content = '';
                        break;
                    case 'external_redpacket':
                        $show = $val['redpacket']['wish'];
                        $content = json_encode($val['redpacket']);
                        break;
                    case 'redpacket':
                        $show = $val['redpacket']['wish'];
                        $content = json_encode($val['redpacket']);
                        break;
                    case 'location':
                        //位置消息
                        $show = $val[$val['msgtype']]['address'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'link':
                        //链接消息
                        $show = $val[$val['msgtype']]['link_url'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'mixed':
                        //会话记录
                        $show = "";
                        foreach ($val['mixed']['item'] as $k=>$item)
                        {
                            if($item['type'] == 'image')
                            {
                                $cont = json_decode($item['content'],true);
                                $sdkFileId = $cont["sdkfileid"];
                                $fileext = 'png';
                                $val['mixed']['item'][$k]['mediaUrl'] = $domain. "/uploads/workwx/{$val['msgtype']}/".date('Ymd')."/{$val['msgid']}.{$fileext}";
                                // $filename = "{$path}{$val['msgid']}.{$fileext}";
                            }
                            if($item['type'] == 'text')
                            {
                                $cont = json_decode($item['content'],true);
                                $val['mixed']['item'][$k]['content'] = $cont['content'];
                            }
                        }
                        $content = json_encode($val['mixed']['item']);
                        break;
                    case 'revoke':
                        //撤回消息
                        $show = $val[$val['msgtype']]['pre_msgid'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'card':
                        //名片消息
                        $show = $val[$val['msgtype']]['corpname'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'weapp':
                        //小程序消息
                        $show = $val[$val['msgtype']]['displayname'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'chatrecord':
                        //会话记录消息
                        $show = $val[$val['msgtype']]['title'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'todo':
                        //待办消息
                        $show = $val[$val['msgtype']]['title'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'vote':
                        //投票消息
                        $show = $val[$val['msgtype']]['votetitle'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'sphfeed':
                        //视频号消息
                        $show = $val[$val['msgtype']]['sph_name'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'meeting':
                        //视频号消息
                        $show = $val[$val['msgtype']]['topic'];
                        $content = json_encode($val[$val['msgtype']]);
                        break;
                    case 'meeting_notification':
                        //视频号消息
                        $show = $val['info']['content'];
                        $content = json_encode($val['info']);
                        break;
                    case 'docmsg':
                        $show = $val['doc']['title'];
                        $content = json_encode($val["doc"]);
                        break;

                    default:
                        if(!isset($val[$val['msgtype']]['content']))
                        {
                            logging(__FILE__,$chatList);
                            // (new EnterpriseWeChat())->EnterpriseWechatPushMessage('企微通知',$val['msgid'].'企微聊天记录拉取失败：',[],['LaoSan1'],Config('CRM_URL'));
                            exit;
                        }
                        break;
                }
//                if($filename && !file_exists($filename)){
//                    $msgaudit->downloadMedia($sdkFileId, $filename);
//                }
//                if($val['msgtype'] == 'meeting_voice_call' || $val['msgtype'] == 'voice')
//                {
//                    $this->amr_mp3($show);
//                    $show = explode('.amr',$show)[0].'.mp3';
//
//                    if(file_exists($filename)){
//                        unlink($filename);
//                    }
//                    $filename = explode('.amr',$filename)[0].'.mp3';
//
//                }
                $file_status = 2;
                if (strpos($show, '/uploads/workwx')!== false) {
                    $file_status = 1;
                }
                $data = [
                    'msgid'   => $val['msgid'],
                    'action'  => $val['action'],
                    'from'    => $val['from'],
                    'tolist'  => isset($val['tolist']) ? json_encode($val['tolist']) : '',
                    'roomid'  => isset($val['roomid']) ? $val['roomid']: '',
                    'msgtime' => date('Y-m-d H:i:s', $val['msgtime'] / 1000),
                    'msgtype' => $val['msgtype'],
                    'show'    => $show,
                    'content' => $content,
                    'seq'     => $val['seq'],
                    'addtime' => date('Y-m-d H:i:s'),
                    'text' => json_encode($val),
                    'file_status' => $file_status
                ];


                $records = Db::connect('CRMDbConfig')->name('corp_wechat_records')->where(['msgid'=>$data['msgid']])->find();
                if(!$records)
                {
                    Db::connect('CRMDbConfig')->name('corp_wechat_records')->insert($data);
                    $to = json_decode($data['tolist'])[0];
                    if(strpos($data['from'],'wmgpm') !== false)
                    {
                        $id = Db::connect('CRMDbConfig')->name('corp_wechat')->where(['external_userid'=>$data['from'],'userid'=>$to])->value('id');
                        //如何客户删除  然后客户有发了消息状态恢复
                        Db::connect('CRMDbConfig')->name('corp_wechat')->where('id',$id)->update(['status'=>1]);

                    }else{
                        $id = Db::connect('CRMDbConfig')->name('corp_wechat')->where(['external_userid'=>$to,'userid'=>$data['from']])->value('id');
                    }
                    Db::connect('CRMDbConfig')->name('corp_wechat')->where('id',$id)->update(['last_update_time'=>date('Y-m-d H:i:s')]);
                }
            }
        }


        //$this->file_processing();
        $this->success('succ');
    }

    public function amr_mp3($await_amr){
        $amr = ROOT_PATH.'public'.$await_amr;
        $amr_arr = explode('.amr',$amr);
        $mp3 = $amr_arr[0].'.mp3';

        if(file_exists($mp3) == true){

        }else{
            $command = "/www/server/ffmpeg/ffmpeg-6.1/ffmpeg -i $amr $mp3";
            system($command,$error);
            @unlink($amr);
        }
    }


    //文件处理，会话存档只能保存5天
    public function file_processing()
    {
        $msgaudit = include_once(EXTEND_PATH . 'workwx/library/src/Api/Struct/Msgaudit/Msgaudit.php');
        $msgaudit->call($this->corpId, $this->secret, $this->privateKey);
        $where = ['show'=>['like','%/uploads/workwx%'],'file_status'=>1,'msgtime'=>['>',date('Y-m-d H:i:s',strtotime('-5 day'))]];
        $post       =   $this->request->post();
        if(isset($post['id']) && $post['id'])
        {
            $where['id'] = ['in',$post['id']];
        }
        $records = Db::connect('CRMDbConfig')->name('corp_wechat_records')->where($where)->order('id desc')->limit(8)->select();
        $dir = ROOT_PATH . "public";
        foreach ($records as $key=>$row)
        {
            $filename = $dir.$row['show'];
            $test = json_decode($row['text'],true);
            $sdkFileId = $test[$row['msgtype']]["sdkfileid"];
            if($filename && !file_exists($filename)){
                $msgaudit->downloadMedia($sdkFileId, $filename);
            }
            if($row['msgtype'] == 'meeting_voice_call' || $row['msgtype'] == 'voice')
            {
                $this->amr_mp3($row['show']);
                $show = explode('.amr',$row['show'])[0].'.mp3';
                Db::connect('CRMDbConfig')->name('corp_wechat_records')->where(['id'=>$row['id']])->update(['show'=>$show]);
                if(file_exists($filename)){
                    unlink($filename);
                }
            }
            Db::connect('CRMDbConfig')->name('corp_wechat_records')->where(['id'=>$row['id']])->update(['file_status'=>2]);
        }
        $count = Db::connect('CRMDbConfig')->name('corp_wechat_records')->where($where)->count();
        $this->success('剩余待同步数量'.$count);
    }




    //获取企业微信聊天记录
    public function get_corp_wechat_records()
    {
        $param       =   $this->request->param();
        $where['msgtime'] = ['between',$param['time']];
        if(!empty($param['msgid']))
        {
            $where['msgid'] = $param['msgid'];
        }
        if(!empty($param['msgtype']))
        {
            $where['msgtype'] = $param['msgtype'];
        }
        if(!empty($param['show']))
        {
            $where['show'] = ['like',"%{$param['show']}"];
        }
        if($param['userid'] && $param['external_userid'])
        {
            $corp_wechat_records = Db::name('corp_wechat_records')->where($where)->where("(`from`='{$param['userid']}' or `tolist` like '%{$param['userid']}%') and (`from`='{$param['external_userid']}' or `tolist` like '%{$param['external_userid']}%')")->order('id asc')->page($this->page,$this->rows)->select();
        }else{
            $corp_wechat_records = Db::name('corp_wechat_records')->where($where)->order('id asc')->page($this->page,$this->rows)->select();
        }
        $a = Db::name('corp_wechat_records')->getLastSql();

        $this->success('succ',$corp_wechat_records);
    }



}
